/*
 * Copyright (C) 2007-2012 Geometer Plus <contact@geometerplus.com>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

package org.geometerplus.fbreader;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.Environment;

import org.geometerplus.zlibrary.core.options.ZLStringOption;
import org.geometerplus.zlibrary.core.util.SystemInfo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

public abstract class Paths {


    public static ZLStringOption BooksDirectoryOption() {
        return new ZLStringOption("Files", "BooksDirectory", cardDirectory() + "/17KReader");
    }

    public static ZLStringOption FontsDirectoryOption() {
        return new ZLStringOption("Files", "FontsDirectory", cardDirectory() + "/Fonts");
    }

    public static ZLStringOption WallpapersDirectoryOption() {
        return new ZLStringOption("Files", "WallpapersDirectory", cardDirectory() + "/Wallpapers");
    }

    public static String cacheDirectory() {
        return BooksDirectoryOption().getValue() + "/.cache";
    }

    public static String networkCacheDirectory() {
        return cacheDirectory() + "/cache";
    }

    public static String systemShareDirectory() {
        return "/system/usr/share/FBReader";
    }

    public static SystemInfo systemInfo(Context context) {

        final Context appContext = context.getApplicationContext();

        return new SystemInfo() {
            //内部临时目录
            public String tempDirectory() {
                return internalTempDirectoryValue(appContext);
            }

            //网络缓存目录
            public String networkCacheDirectory() {
                return tempDirectory() + "/cache";
            }
        };
    }


    private static String internalTempDirectoryValue(Context context) {
        String value = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
            value = getExternalCacheDirPath(context);
        }
        return value != null ? value : (mainBookDirectory() + "/.FBReader");
    }

    @TargetApi(Build.VERSION_CODES.FROYO)
    private static String getExternalCacheDirPath(Context context) {
        final File d = context != null ? context.getExternalCacheDir() : null;
        if (d != null) {
            d.mkdirs();
            if (d.exists() && d.isDirectory()) {
                return d.getPath();
            }
        }
        return null;
    }

    public static String mainBookDirectory() {
        return defaultBookDirectory();
    }

    public static String cardDirectory() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            return Environment.getExternalStorageDirectory().getPath();
        }

        final List<String> dirNames = new LinkedList<String>();
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader("/proc/self/mounts"));
            String line;
            while ((line = reader.readLine()) != null) {
                final String[] parts = line.split("\\s+");
                if (parts.length >= 4 &&
                        parts[2].toLowerCase().indexOf("fat") >= 0 &&
                        parts[3].indexOf("rw") >= 0) {
                    final File fsDir = new File(parts[1]);
                    if (fsDir.isDirectory() && fsDir.canWrite()) {
                        dirNames.add(fsDir.getPath());
                    }
                }
            }
        } catch (Throwable e) {
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                }
            }
        }

        for (String dir : dirNames) {
            if (dir.toLowerCase().indexOf("media") > 0) {
                return dir;
            }
        }
        if (dirNames.size() > 0) {
            return dirNames.get(0);
        }

        return Environment.getExternalStorageDirectory().getPath();
    }

    private static String defaultBookDirectory() {
        return cardDirectory() + "/Books";
    }
}

